package com.zqh.myfmmall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqh.myfmmall.dao.UsersDao;
import com.zqh.myfmmall.defult.DefultEntityPropertyValue;
import com.zqh.myfmmall.entity.Users;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.service.UsersService;
import com.zqh.myfmmall.utils.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;

/**
 * 用户 (Users)表服务实现类
 *
 * @author KONO 曾淇杭哒！
 * @since 2022-01-20 02:35:50
 */
@Service("usersService")
public class UsersServiceImpl extends ServiceImpl<UsersDao, Users> implements UsersService {
    @Override
    public Result regist(String username, String password) {
        Users user = query().eq("username", username).one();
        if (user != null) {
            return Result.fail("用户名已存在");
        }

        String randomNickName = UUID.randomUUID().toString().substring(0,15);
        Users newUser = new Users();
        newUser.setNickname(randomNickName);
        newUser.setUsername(username);
        newUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        newUser.setUserImg(DefultEntityPropertyValue.userImg);
        save(newUser);
        return Result.success("注册成功！");
    }

    @Override
    public Result login(String username, String password) {
        Result result = null;
        Users user = query().eq("username", username).one();
        if (user == null) {
            result = Result.fail("用户名错误");
        }else {
            if (user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
                HashMap<String, Object> claimsMap = new HashMap<>();
                claimsMap.put("userId",user.getUserId());
                String token = JwtUtil.generate(claimsMap);
                result = Result.success("登录成功！",token);
            }else{
                result = Result.fail("密码错误");
            }
        }
        return result;
    }
}

